//
//  DetailSheetView.swift
//  KoiAccounting
//
//  记账明细半弹层
//  Created by 纪洪文 on 17.04.25.
//

import SwiftUI

struct DetailRecordView: View {
    
    var onDeleteClick:() -> Void
    var onEditClick:() -> Void
    
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.presentToast) var presentToast
    @State var deleteDetail: AccountingDetailCombine? = nil
    @State var editDetail: AccountingDetailCombine? = nil
    @State var amountEdit: AccountingDetailCombine? = nil
    @State var remarkEdit: AccountingDetailCombine? = nil
    @State var deleteConfirm = false
    @State var showCalendarSheet = false
    
    @StateObject private var viewModel: DetailRecordViewModel
    
    init(item: AccountingDetailCombine, onDeleteClick:@escaping () -> Void, onEditClick:@escaping () -> Void) {
        self._viewModel = StateObject(wrappedValue: DetailRecordViewModel(detail: item))
        self.onDeleteClick = onDeleteClick
        self.onEditClick = onEditClick
    }
    
    
    
    var body: some View {
        VStack (spacing: 30){
            VStack {
                NavigationLink(
                    destination: {
                        QuickEditCategoryView(
                            selectedCategory: viewModel.detail.category,
                            categoryType: getCategoryType(),
                            onCategorySelect: { selectedCategory in
                                viewModel.updateCategory(selectedCategory: selectedCategory)
                            }
                        )
                    },
                    label: {
                        // 类别
                        DetailSheetItemView(itemType: .category, item: $viewModel.detail)
                    }
                )
                Button(action: {
                    amountEdit = viewModel.detail
                }) {
                    // 金额
                    DetailSheetItemView(itemType: .amount, item: $viewModel.detail)
                }
                
                Button(action: {
                    showCalendarSheet = true
                    
                }) {
                    // 日期
                    DetailSheetItemView(itemType: .date, item: $viewModel.detail)
                }

                Button(action: {
                    remarkEdit = viewModel.detail
                }) {
                    // 备注
                    DetailSheetItemView(itemType: .remark, item: $viewModel.detail)
                }
                
                NavigationLink(destination: {
                    QuickEditBookView(detail: viewModel.detail, onSelectedBook: { selectedBook in
                        viewModel.selectedBook = selectedBook
                        KoiEvent.homeReload.send()
                    })
                }, label: {
                    // 账本
                    DetailSheetItemView(itemType: .book, item: $viewModel.detail)
                })
            }
            .padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 0))
            .background(Color.koiColorBackgroundItem)
            .cornerRadius(16)

            Spacer()
            
            HStack (spacing:0){
                Button(action: {
                    deleteDetail = viewModel.detail
                }) {
                    HStack {
                        Image("koi_ic_delete")
                            .resizable()
                            .frame(width: 16, height: 16)
                        Text("删除")
                            .font(.system(size: 15))
                            .foregroundColor(Color.koiColorPrimary)
                    }
                    .padding(EdgeInsets(top: 15, leading: 45, bottom: 15, trailing: 45))
                    .frame(maxWidth: .infinity)
                    .background(Color.koiColorPrimary.opacity(0.04))
                    .cornerRadius(40)
                }
                   
                Spacer()
                
                Button(action: {
                    editDetail = viewModel.detail
                }) {
                    HStack {
                        Image("koi_ic_pencil")
                            .resizable()
                            .frame(width: 16, height: 16)
                        Text("编辑")
                            .font(.system(size: 15))
                            .foregroundColor(Color.koiColorTitle)
                    }
                    .padding(EdgeInsets(top: 15, leading: 45, bottom: 15, trailing: 45))
                    .frame(maxWidth: .infinity)
                    .background(Color.koiColorBackgroundItem)
                    .cornerRadius(40)
                }
            }
        }
        .actionSheet(item: $deleteDetail) { deleteDetail in
            ActionSheet(
                title: Text("确定要删除「\(deleteDetail.getTitle())」吗？"),
                message: Text("记账数据删除后不可恢复，请确认是否删除？"),
                buttons: [
                    .destructive(Text("确认删除")) {
                        viewModel.delete(detail: deleteDetail)
                    },
                    .cancel(Text("取消"))
                ])
        }
        .sheet(item: $editDetail, onDismiss: { loadDetail() }) { editDetail in
            AddAccountingView(selectedDetail: editDetail).presentationDetents([.large])
        }
        .koiSheet(item: $amountEdit, onDismiss: { loadDetail() }) { detail in
            QuickEditAmountView(detail: detail)
        }
        .koiSheet(isPresented: $showCalendarSheet, onDismiss: { loadDetail() }) {
            CalendarView(selectedDate: $viewModel.selectedDate) { newDate in
                viewModel.updateDate(newDate:newDate)
            }
        }
        .koiSheet(item: $remarkEdit, onDismiss: { loadDetail()} ) { remarkEdit in
            QuickEditRemarkView(detail: remarkEdit)
        }
        .koiToolbar(title: Text("明细详情"))
        .padding(EdgeInsets(top: 16, leading: 20, bottom: 16, trailing: 20))
        .onChange(of: viewModel.updateState) { value in
            if value == "" { return }
            if value == "success" {
                viewModel.updateState = ""
                loadDetail()
                presentToast(.init(message: "已更新"))
                KoiEvent.homeReload.send()
            }
        }
        .onChange(of: viewModel.deleteState) { value in
            if value == "" { return }
            if value == "success" {
                presentToast(.init(message: "已删除"))
                presentationMode.wrappedValue.dismiss()
            }
        }
        .onAppear {
            loadDetail()
        }
    }
    
    func loadDetail() {
        viewModel.loadDetail()
    }
    
    func getCategoryType() -> CategoryType {
        return viewModel.detail.category.getCategoryType()
    }
}

@available(iOS 18, *)
#Preview {
    @Previewable @State var item = AccountingDetailCombine.previewData()
    DetailRecordView(item: item, onDeleteClick: {}, onEditClick: {})
}
